import kingUrl from '@/servers/kingUrl'
import { getCookie } from '@/storage'
import { Toast } from 'antd-mobile'
import axios from 'axios'

/**
 * 获取文件后缀名
 * @param filename
 * @returns {string}
 */
export function getSuffix(filename: string): string {
    const pos = filename.lastIndexOf('.')
    let suffix = ''
    if (pos !== -1) {
        suffix = filename.substring(pos)
    }
    return suffix
}

/** oss 上传方法 */
export default async function ossUpload(files: File): Promise<any> {
    if (!files) {
        return undefined
    }
    const header: any = {}
    const tooken = getCookie('TOKEN')
    if (tooken !== undefined && tooken !== '' && tooken !== null) {
        header.Authorization = `Bearer ${tooken}`
    }
    const res = await axios({
        url: `${kingUrl}osses/token`,
        method: 'get',
        params: { type: 10 },
        headers: {
            'Content-Type': 'application/json',
            'X-Client-Type': 'mobile',
            // 'X-Test-Domain': 'wj.edum.work.woczx.com', //发版注释
            ...header,
        },
    })
    const { data } = res || {}
    const { host, dir, policy, accessid, callback, signature, name } = data
    const formData = new FormData()
    const suffix = getSuffix(files.name)
    formData.append('key', dir + name + suffix)
    formData.append('name', files.name)
    formData.append('policy', policy)
    formData.append('OSSAccessKeyId', accessid)
    formData.append('success_action_status', '200')
    formData.append('callback', callback)
    formData.append('signature', signature)
    formData.append('file', files)
    return new Promise((resolve, reject) => {
        Toast.show({
            icon: 'loading',
            content: '上传中…',
            maskClickable: false,
            duration: 0,
        })
        axios
            .post(`${host}`, formData, {
                headers: { 'Content-Type': 'multipart/form-data' },
                timeout: 36000000,
                onUploadProgress(progressEvent) {
                    if (progressEvent.lengthComputable) {
                        // 属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量
                        // 如果lengthComputable为false，就获取不到progressEvent.total和progressEvent.loaded
                        // const complete = `${((progressEvent.loaded / progressEvent.total) * 100) | 0  }%`
                        // window.showLoading(`文件上传中，请勿关闭浏览器！${complete}`, complete)
                    }
                },
            })
            .then(val => {
                Toast.clear()
                // eslint-disable-next-line no-shadow, @typescript-eslint/no-shadow
                const { data } = val || {}
                const { file } = data || {}
                if (file) {
                    resolve({
                        url: file,
                        name: files.name,
                        thumbnailUrl: `${file}?x-oss-process=video/snapshot,t_1000,m_fast`,
                    })
                    // if (window.hasOwnProperty('hideLoading')) {
                    //     window.hideLoading()
                    // }
                    // this.setState({ video: file, video_name: files.name })
                } else {
                    Toast.show('上传失败')
                }
            })
            .catch(err => {
                Toast.clear()
                reject(err)
                // if (window.hasOwnProperty('hideLoading')) {
                //     window.hideLoading()
                // }
            })
    })
}
